<template>
  <div class="chart-wrap w-full h-full" :class="`${chatClassName}`"></div>
</template>

<script>
import _ from 'lodash'
import NP from 'number-precision'
import { echartColor, bgColor, lineColor } from '@/utils/study.js'
import ChartWatcherMixin from '@/mixins/ChartWatcherMixin.js'
import {
  formatterForGroup,
  formatterForGroupAccuracy,
  formatterForSeriesAllGroupAccuracy,
  getSeriesForLineTypeThree,
  getSeriesForLineTypeTwo,
  getSeriesForLineTypeTwoWithMetrics,
  getMetrics
} from '@/utils/study.js'

export default {
  name: 'RangeLine',
  mixins: [ChartWatcherMixin],
  props: {
    groups: {
      type: Array,
      default: () => []
    },

    yValueIncrement: {
      type: Number,
      default: 1
    },

    // eslint-disable-next-line vue/require-default-prop
    yMin: {
      type: Number
    },
    // eslint-disable-next-line vue/require-default-prop
    yMax: {
      type: Number
    },
    colors: {
      type: Array,
      default: () => echartColor
    },
    yAxisSplitLine: {
      type: Object,
      default: () => ({
        show: true,
        lineStyle: {
          color: [
            ...echartColor.flatMap((color) => [
              color,
              ...Array(9).fill(bgColor) // 每个颜色后面跟随9个白色
            ])
          ],

          width: 1,
          // type: 'solid'
          type: 'dashed'
        }
      })
    },
    yAxisAxisLabelFormatter: {
      type: Function,
      default: (value) => {
        if (Number.isInteger(value)) {
          return value
        }
        return '' // 隐藏其他非整数刻度
      }
    },
    grid: {
      type: Object,
      default: () => ({
        borderWidth: 0, // 确保没有边框
        show: true,
        left: 25,
        right: 0,
        top: 8,
        bottom: 110
      })
    },
    /**
     * 默认 1
     * @despction 1 分组折线
     * @despction 2 分组杀前一期准确折线
     * @despction 3 某一系列所有分组，杀前一期准确折线
     * @despction 4 × (复用3)所有系列所有分组，平铺情况下，所选的分组，杀前一期准确折线
     * @despction 5 外部传入的 data
     */
    showLineType: {
      type: Number,
      default: 1
    },
    groupMap: {
      type: Object,
      default: () => ({})
    },
    selectGroups: {
      type: Array,
      default: () => []
    },
    seriesData: {
      type: Array,
      default: () => []
    },
    metricsOptions: {
      type: Object,
      default: () => ({
        successValue: 10,
        errorValue: 0,
        successName: '正确',
        errorName: '错误'
      })
    }
  },
  data() {
    return {
      chartOption: {
        color: lineColor,
        grid: this.grid,
        tooltip: {
          trigger: 'axis'
        },
        dataZoom: [
          {
            // startValue: 1,
            // endValue: 49,
            bottom: 10,
            right: 5,
            left: 5
          }
        ],
        xAxis: {
          type: 'category',
          // data: _data.map((e) => e.time),
          data: [],
          axisLabel: {
            // interval: 0, // 使x轴文字显示全
            interval: 'auto', // 自动调整间隔
            rotate: 60
          },
          axisLine: {
            // onZero: false,
            show: false
          },
          axisTick: {
            show: false // 设置为false来隐藏小竖线
          }
        },
        yAxis: {
          type: 'value',
          interval: 0.1, // 步长
          // min: 0, // 起始
          min: this.yMin !== undefined ? this.yMin : 1, // 起始
          max: this.yMax !== undefined ? this.yMax : this.groups.length, // 终止

          data: Array.from({ length: this.groups.length }, (_, index) => index),

          // splitLine: {
          //   show: false,
          // },

          // 网格样式
          splitLine: this.yAxisSplitLine,

          axisLabel: {
            formatter: this.yAxisAxisLabelFormatter
          }
        },

        series: [
          {
            // data: _data.map((e) => e.head),
            data: [],
            type: 'line',
            // 设置线条的颜色
            // lineStyle: {
            //   color: '#91cc75',
            // },
            lineStyle: {
              color: lineColor, // 默认颜色
              width: 1 // 默认线宽
            },
            emphasis: {
              lineStyle: {
                color: lineColor, // 悬停时的颜色
                width: 1 // 悬停时的线宽
              }
              // itemStyle: {
              //   color: "#ff7f50", // 悬停时数据点的颜色
              //   borderColor: "#ff7f50", // 数据点边框颜色
              //   borderWidth: 2, // 数据点边框宽度
              // },
            }
          }
        ]
      }
    }
  },

  computed: {
    selectGroupMap() {
      return _.pick(this.groupMap, this.selectGroups)
    }
  },

  watch: {
    selectGroupMap() {
      this.updateChart()
    }
  },

  methods: {
    // 获取系列数据
    getSeriesData() {
      return _.cloneDeep(this.allValues).map((element) => {
        const value = _.findIndex(this.groups, (group) => _.includes(group, Number(element.number)))
        element.value = value + this.yValueIncrement
        return element
      })
    },

    // 设置准确图的 splitLine 和 axisLabel
    setAccuracySplitLineAndAxisLabel() {
      this.chartOption.yAxis.splitLine = null
      // 备份
      // this.chartOption.yAxis.axisLabel = {
      //   formatter: (value) => (value === 0 ? 'n' : value === 10 ? 'y' : '')
      // }
      this.chartOption.yAxis.axisLabel = null
    },
    // 设置当前分组图数据
    setGroupData() {
      this.chartOption.series[0].data = _.chain(this.allValues)
        .cloneDeep()
        .map((element, index) => {
          // 获取当前数字所在的分组内的 分组Index + yValueIncrement
          element.value = _.chain(this.groups)
            .findIndex((group) => _.includes(group, _.toNumber(element.number)))
            .add(this.yValueIncrement)
            .value()

          if (index > 0) {
            // 获取前一期数字所在的分组内的 分组Index
            element.prevGroupIndex = _.chain(this.allValues)
              .get([index - 1, 'number'])
              .toNumber()
              .thru((prevNumber) => _.findIndex(this.groups, (group) => _.includes(group, prevNumber)))
              .value()
          }

          return element
        })
        .thru((values) => {
          // 统计 value 出现的次数
          const groupedCounts = _.countBy(values, 'value')

          // 统计 value 出现的次数总和
          const total = _.sum(_.values(groupedCounts))

          // 返回 原始数据 和 统计数据 和 总和
          return { values, groupedCounts, total }
        })
        .thru(({ values, groupedCounts, total }) =>
          _.map(values, (sourceData) => {
            // 当前值
            const value = sourceData.value

            // 当前分组出现的次数
            const currentGroupCount = groupedCounts[value]

            // 理论平均值
            const theoreticalAverage = NP.round(NP.divide(total, this.groups.length), 2)

            // 前一期数字所在的分组
            const prevGroupsNumber = _.isNumber(sourceData.prevGroupIndex) ? this.groups[sourceData.prevGroupIndex] : []

            // 当前分组索引
            const groupIndex = value - this.yValueIncrement

            // 当前分组数据
            const groupsNumber = this.groups[groupIndex]

            return {
              // 当前值
              value,
              // 原始数据
              sourceData,
              // 当前分组
              groupsNumber,
              // 前一期数字所在的分组
              prevGroupsNumber,
              // 当前分组出现的次数 和 理论平均值
              chance: {
                currentGroupCount,
                theoreticalAverage
              },
              // 颜色
              itemStyle: { color: this.colors[groupIndex] }
            }
          })
        )
        .value()
    },

    // 设置[前一组杀号准确图]数据
    setGroupAccuracyData() {
      const allValues = getSeriesForLineTypeTwoWithMetrics(this.allValues, this.groups, this.metricsOptions)
      this.chartOption.series[0].data = allValues

      // // 混入 metrics
      // const metrics = getMetrics(allValues.map((e) => e.value), this.metricsOptions)
      // this.chartOption.series[0].data = allValues.map((e) => ({
      //   ...e,
      //   metrics
      // }))

      this.setAccuracySplitLineAndAxisLabel()

      this.chartOption.yAxis.min = -0.1
      this.chartOption.yAxis.max = 10.1
    },

    // 设置 dataZomm 的 startValue 和 endValue
    setDataZoomStartAndEnd() {
      if (!this.allValues.length) {
        this.chartOption.dataZoom[0].startValue = null
        this.chartOption.dataZoom[0].endValue = null
        return
      }
      // const n = _.floor(this.allValues.length / 4)
      const n = _.floor(this.allValues.length / 16)
      const startItem = _.nth(this.allValues, -n)
      const endItem = _.last(this.allValues)
      const startValue = startItem.time
      const endValue = endItem.time

      this.chartOption.dataZoom[0].startValue = startValue
      this.chartOption.dataZoom[0].endValue = endValue
    },

    // 设置同一系列所有分组[前一组杀号准确图]数据
    setSeriesAllGroupAccuracy() {
      // console.log('this.selectGroupMap', this.selectGroupMap)

      const allValues = getSeriesForLineTypeThree(this.allValues, this.selectGroupMap)
      // console.log('allValues', allValues)
      this.chartOption.series[0].data = allValues

      this.setAccuracySplitLineAndAxisLabel()

      this.chartOption.yAxis.min = -0.1
      this.chartOption.yAxis.max = 10.1
    },

    // 设置

    // 设置 xAxis.data
    setXdata() {
      this.chartOption.xAxis.data = this.allValues.map((e) => e.time)
    },

    // 更新图表
    updateChart() {
      if (this.myChart) {
        switch (this.showLineType) {
          case 1: // 分组折线
            this.setGroupData()
            this.chartOption.tooltip.formatter = (params) => formatterForGroup.call(this, params)
            break
          case 2: // 分组杀前一期准确折线
            this.setGroupAccuracyData()
            this.chartOption.tooltip.formatter = (params) => formatterForGroupAccuracy.call(this, params)
            break
          case 3: // 某一系列所有分组，杀前一期准确折线
            this.setSeriesAllGroupAccuracy()
            this.chartOption.tooltip.formatter = (params) => formatterForSeriesAllGroupAccuracy.call(this, params)
            break
          case 5: // 外部传入的 data
            this.chartOption.yAxis.splitLine = {
              show: true,
              lineStyle: {
                color: [
                  '#1890ff',
                  ...[...Array(9)].map((e) => bgColor),
                  '#fc8452' // 根据 -0.1 是否移除
                ],
                // type: 'solid'
                type: 'dashed'
              }
            }

            this.chartOption.series[0].data = this.seriesData.map((item, index) => {
              // console.log(this.colors)
              return {
                ...item,
                itemStyle: { color: item.value === 1 ? '#fc8452' : '#1890ff' }
              }
            })
            break
        }
        this.setDataZoomStartAndEnd()
        this.setXdata()
        // console.log(this.chartOption)
        // 绘制图表
        this.myChart.setOption(this.chartOption)
      }
    }
  }
}
</script>
